#include "clientwindow.h"
#include <QMessageBox>
ClientWindow::ClientWindow(QWidget *parent) : QMainWindow(parent)
{
        init();
}
void ClientWindow::init(){
    setWindowTitle("客户端");
    setGeometry(100, 200, 680, 500);

    connectBtn =  new QPushButton(this);
    connectBtn->setGeometry(50, 50, 80, 30);
    connectBtn->setText("连接");
    connectBtn->setEnabled(true);

    disConnectBtn =  new QPushButton(this);
    disConnectBtn->setGeometry(150, 50, 80, 30);
    disConnectBtn->setText("断开连接");
    disConnectBtn->setEnabled(false);

    QObject::connect(connectBtn, SIGNAL(clicked()), this, SLOT(connectServer()));
    QObject::connect(disConnectBtn, SIGNAL(clicked()), this, SLOT(disConnectServer()));

    receiveMsgLabel = new QLabel(this);
    receiveMsgLabel->setGeometry(100, 90, 80, 30);
    receiveMsgLabel->setText("收到：");

    receiveTextEdit = new QPlainTextEdit(this);
    receiveTextEdit->setGeometry(100, 120, 500, 100);

    sendMsgLabel = new QLabel(this);
    sendMsgLabel->setGeometry(100, 230, 80, 30);
    sendMsgLabel->setText("发送：");

    sendTextEdit = new QPlainTextEdit(this);
    sendTextEdit->setGeometry(100, 260, 500, 100);

    sendBtn = new QPushButton(this);
    sendBtn->setText("发送");
    sendBtn->setGeometry(100, 380, 80, 30);
    QObject::connect(sendBtn, SIGNAL(clicked()), this, SLOT(slotSendMsg()));

}
//连接服务端
void ClientWindow::connectServer(){
    if(client == nullptr){
        client = new Client("127.0.0.1", 8088, this);
        //绑定数据接收
        QObject::connect(client, SIGNAL(signalReceiveMsg(QString)), this, SLOT(slotReceiveMsg(QString)));
    }
    client->connect();
    connectBtn->setEnabled(false);
    disConnectBtn->setEnabled(true);
}

//断开连接
void ClientWindow::disConnectServer(){
    client->disConnect();
    connectBtn->setEnabled(true);
    disConnectBtn->setEnabled(false);
}
//发送消息
void ClientWindow::slotSendMsg(){
    if(client->getSocket()->isOpen()){
        QString s = sendTextEdit->toPlainText();
        client->getSocket()->write(s.toUtf8().data());
        sendTextEdit->clear();
    }else{
        QMessageBox::warning(this, "警告", "连接已断开");
    }

}
//接收消息
void ClientWindow::slotReceiveMsg(QString msg){
    receiveTextEdit->appendPlainText(msg);
}


